package com.heima.kafka.sample;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

/**
 * 生产者
 */
public class ProducerQuickStart {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 1. kafka连接配置信息
        Properties properties = new Properties();
        // kafka链接地址
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.133.101:9092");
        // key 和 value的序列化
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        // ack 消息确认机制
        properties.put(ProducerConfig.ACKS_CONFIG,"all");
        // 重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG,10);
        // 数据压缩
        properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, "snappy");


        // 2. 创建kafka生产者对象
        KafkaProducer<String, String> producer = new KafkaProducer<>(properties);
        // 3. 发送消息
        for (int i = 0; i < 10; i++) {
            ProducerRecord<String, String> kvProducerRecord = new ProducerRecord<>("itcast-topic-input","hello kafka");
            producer.send(kvProducerRecord);
        }
//        ProducerRecord<String, String> kvProducerRecord = new ProducerRecord<>("topic-first","key-001","hello kafka");
//        RecordMetadata recordMetadata = producer.send(kvProducerRecord).get();
//        System.out.println(recordMetadata.offset());

//        // 异步条件发送
//        producer.send(kvProducerRecord, new Callback() {
//            @Override
//            public void onCompletion(RecordMetadata recordMetadata, Exception e) {
//                if (e != null){
//                    System.out.println("记录异常信息到日志表中");
//                }
//                System.out.println(recordMetadata.offset());
//            }
//        });
        // 4. 关闭消息通道
        producer.close();
    }
}
